// src/pages/Home/MetadataDriven/DataManagement.jsx
import React, { useState, useEffect } from 'react';
import {
  Table, Card, Button, Form, Input, Select,
  DatePicker, Switch, InputNumber, Checkbox,
  Row, Col, Drawer, Tag, Space, message,
  Flex
} from 'antd';
import {
  SearchOutlined,
  DatabaseOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined
} from '@ant-design/icons';

// 根据字段类型确定表单组件
const getFormFieldComponent = (field) => {
  switch (field.type) {
    case 'string':
      if (field.enum) {
        return (
          <Select>
            {field.enum.map(option => (
              <Select.Option key={option} value={option}>
                {option}
              </Select.Option>
            ))}
          </Select>
        );
      }
      return <Input />;

    case 'number':
      return <InputNumber style={{ width: '100%' }} />;

    case 'date':
      return <DatePicker style={{ width: '100%' }} />;

    case 'boolean':
      return <Switch />;

    case 'text':
      return <Input.TextArea />;

    default:
      return <Input />;
  }
};

// 根据字段类型确定筛选组件
const getFilterComponent = (field) => {
  switch (field.type) {
    case 'string':
      if (field.enum) {
        return (
          <Select allowClear placeholder={`筛选${field.label}`}>
            {field.enum.map(option => (
              <Select.Option key={option} value={option}>
                {option}
              </Select.Option>
            ))}
          </Select>
        );
      }
      return <Input placeholder={`筛选${field.label}`} />;

    case 'number':
      return (
        <Flex gap="small">
          <InputNumber placeholder="最小值" style={{ width: '45%' }} />
          <Input placeholder="-" style={{ width: '10%', textAlign: 'center', border: 'none' }} disabled />
          <InputNumber placeholder="最大值" style={{ width: '45%' }} />
        </Flex>
      );

    case 'date':
      return <DatePicker.RangePicker style={{ width: '100%' }} />;

    case 'boolean':
      return (
        <Select allowClear placeholder={`筛选${field.label}`}>
          <Select.Option value={true}>是</Select.Option>
          <Select.Option value={false}>否</Select.Option>
        </Select>
      );

    default:
      return <Input placeholder={`筛选${field.label}`} />;
  }
};

// 元数据驱动的数据管理组件
const MetadataDrivenDataManagement = () => {
  const [dataSources, setDataSources] = useState([]);
  const [selectedDataSource, setSelectedDataSource] = useState(null);
  const [tableData, setTableData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filterForm] = Form.useForm();
  const [dataForm] = Form.useForm();

  // 模拟元数据
  const mockMetadata = {
    id: 'sales_data',
    name: '销售数据表',
    fields: [
      {
        key: 'id',
        label: 'ID',
        type: 'number',
        required: true,
        editable: false,
        searchable: true
      },
      {
        key: 'customerName',
        label: '客户名称',
        type: 'string',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'product',
        label: '产品',
        type: 'string',
        required: true,
        editable: true,
        searchable: true,
        enum: ['产品A', '产品B', '产品C', '产品D']
      },
      {
        key: 'amount',
        label: '金额',
        type: 'number',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'date',
        label: '日期',
        type: 'date',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'status',
        label: '状态',
        type: 'string',
        required: true,
        editable: true,
        searchable: true,
        enum: ['已下单', '已发货', '已完成', '已取消']
      },
      {
        key: 'isVip',
        label: 'VIP客户',
        type: 'boolean',
        required: false,
        editable: true,
        searchable: true
      },
      {
        key: 'notes',
        label: '备注',
        type: 'text',
        required: false,
        editable: true,
        searchable: false
      }
    ]
  };

  // 模拟数据
  const mockData = [
    {
      id: 1,
      customerName: '张三',
      product: '产品A',
      amount: 1200,
      date: '2023-11-15',
      status: '已完成',
      isVip: true,
      notes: '重要客户'
    },
    {
      id: 2,
      customerName: '李四',
      product: '产品B',
      amount: 800,
      date: '2023-11-16',
      status: '已发货',
      isVip: false,
      notes: ''
    },
    {
      id: 3,
      customerName: '王五',
      product: '产品C',
      amount: 2500,
      date: '2023-11-17',
      status: '已下单',
      isVip: true,
      notes: '大额订单'
    }
  ];

  useEffect(() => {
    // 模拟加载数据源
    setDataSources([mockMetadata]);
    setSelectedDataSource(mockMetadata);
    setTableData(mockData);
    setFilteredData(mockData);
  }, []);

  // 生成表格列
  const generateTableColumns = () => {
    if (!selectedDataSource) return [];

    return selectedDataSource.fields.map(field => ({
      title: field.label,
      dataIndex: field.key,
      key: field.key,
      render: (text, record) => {
        if (field.type === 'boolean') {
          return text ? '是' : '否';
        }
        if (field.type === 'date') {
          // 确保日期格式正确
          if (text && typeof text === 'string') {
            return text; // 已经是字符串格式的日期
          }
          if (text && text instanceof Date) {
            return text.toISOString().split('T')[0]; // 转换为 YYYY-MM-DD 格式
          }
          return text || '';
        }
        return text;
      }
    })).concat([
      {
        title: '操作',
        key: 'action',
        render: (_, record) => (
            <Space size="middle">
              <Button
                  type="link"
                  icon={<EyeOutlined />}
                  onClick={() => handleView(record)}
              >
                查看
              </Button>
              <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => handleEdit(record)}
              >
                编辑
              </Button>
            </Space>
        ),
      }
    ]);
  };

  // 生成筛选表单
  const renderFilterForm = () => {
    if (!selectedDataSource) return null;

    const searchableFields = selectedDataSource.fields.filter(field => field.searchable);

    return (
      <Form form={filterForm} layout="vertical" onFinish={handleSearch}>
        <Row gutter={16}>
          {searchableFields.map(field => (
            <Col span={6} key={field.key}>
              <Form.Item name={field.key} label={field.label}>
                {getFilterComponent(field)}
              </Form.Item>
            </Col>
          ))}
          <Col span={6}>
            <Form.Item label="操作">
              <Space>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleResetFilters}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    );
  };

  // 生成数据编辑表单
  const renderDataForm = () => {
    if (!selectedDataSource || !editingRecord) return null;

    const editableFields = selectedDataSource.fields.filter(field => field.editable);

    return (
      <Form form={dataForm} layout="vertical">
        <Row gutter={16}>
          {editableFields.map(field => (
            <Col span={12} key={field.key}>
              <Form.Item
                name={field.key}
                label={field.label}
                rules={[{ required: field.required, message: `请输入${field.label}` }]}
              >
                {getFormFieldComponent(field)}
              </Form.Item>
            </Col>
          ))}
        </Row>
      </Form>
    );
  };

  const handleSearch = async (values) => {
    // 实际项目中这里会调用API进行搜索
    message.success('搜索功能已触发');
  };

  const handleResetFilters = () => {
    filterForm.resetFields();
    setFilteredData(tableData);
  };

  const handleTableChange = (pager) => {
    setPagination({
      ...pagination,
      current: pager.current,
    });
  };

  const handleView = (record) => {
    setEditingRecord(record);
    dataForm.setFieldsValue(record);
    setIsDrawerVisible(true);
  };

  const handleEdit = (record) => {
    setEditingRecord(record);
    dataForm.setFieldsValue(record);
    setIsDrawerVisible(true);
  };

  const handleCreate = () => {
    setEditingRecord(null);
    dataForm.resetFields();
    setIsDrawerVisible(true);
  };

  const handleSave = () => {
    dataForm.validateFields().then(values => {
      // 实际项目中这里会调用API保存数据
      message.success('数据保存成功');
      setIsDrawerVisible(false);
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <Space>
            <DatabaseOutlined />
            元数据驱动数据管理
          </Space>
        }
        extra={
          <Select
            style={{ width: 200 }}
            placeholder="选择数据源"
            value={selectedDataSource?.id || undefined}
            options={dataSources.map(source => ({
              label: source.name,
              value: source.id
            }))}
            onChange={(value) => {
              const source = dataSources.find(s => s.id === value);
              if (source) {
                setSelectedDataSource(source);
              }
            }}
            loading={loading}
          />
        }
      >
        {selectedDataSource && (
          <>
            <Card
              title={`数据源: ${selectedDataSource.name}`}
              size="small"
              extra={
                <Space>
                  <Tag color="blue">
                    字段数: {selectedDataSource.fields.length}
                  </Tag>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleCreate}
                  >
                    新增记录
                  </Button>
                </Space>
              }
            >
              <div style={{ marginBottom: 16 }}>
                {renderFilterForm()}
              </div>

              <Table
                dataSource={filteredData}
                columns={generateTableColumns()}
                rowKey="id"
                loading={loading}
                pagination={{
                  ...pagination,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
                onChange={handleTableChange}
              />
            </Card>
          </>
        )}
      </Card>

      <Drawer
        title={editingRecord ? "编辑数据" : "新增数据"}
        placement="right"
        onClose={() => setIsDrawerVisible(false)}
        open={isDrawerVisible}
        width={600}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setIsDrawerVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button type="primary" onClick={handleSave}>
              保存
            </Button>
          </div>
        }
      >
        {renderDataForm()}
      </Drawer>
    </div>
  );
};

export default MetadataDrivenDataManagement;
